package com.dyh.quickdemozwei.controller;

import com.google.common.collect.Lists;
import org.apache.commons.io.IOUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/wxsph")
public class WxsphMessageController {

    @RequestMapping("/messgae")
    public Object messgae(HttpServletRequest request) throws IOException {
        if ( "GET".equals(request.getMethod())){
            System.out.println("GET请求");

            String signature = request.getParameter("signature");
            String timestamp = request.getParameter("timestamp");
            String echostr = request.getParameter("echostr");

            String token = "5g65Y08x4oFuEnQQXMYdcILgISBj";



            String nonce = request.getParameter("nonce");
            List<String> list = Lists.newArrayList(token, timestamp, nonce);
            List<String> sortedList = list.stream().sorted().collect(Collectors.toList());
            String joinStr = sortedList.stream().collect(Collectors.joining(""));

            System.out.println(getSHA1(joinStr));

            return echostr;

        }
        if ("POST".equals(request.getMethod())){
            System.out.println("POST请求");
            InputStream in = request.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8));
            String content = IOUtils.toString(reader);
            System.out.println(content);
        }
        System.out.println();
        return "dy";
    }


    public static String getSHA1(String input) {
        try {
            // 创建一个MessageDigest实例并指定算法为SHA-1
            MessageDigest md = MessageDigest.getInstance("SHA-1");

            // 将输入字符串转换为字节数组
            byte[] messageDigest = md.digest(input.getBytes(StandardCharsets.UTF_8));

            // 将字节数组转换为十六进制字符串
            BigInteger number = new BigInteger(1, messageDigest);
            String hashtext = number.toString(16);

            // 确保结果总是32个字符长，如果不足32位则前面补0
            while (hashtext.length() < 32) {
                hashtext = "0" + hashtext;
            }

            return hashtext;
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }


}
